import editForm from "../form/index.vue";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import { cloneDeep, deviceDetection } from "@pureadmin/utils";
import { computed, ref, type Ref, reactive } from "vue";
import { ElMessageBox } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import type { PaginationProps } from "@pureadmin/table";
import type { PlanTaskItem } from "./types";

export function useplanTasks(tableRef: Ref) {
  const form = reactive({
    name: "",
    cronExpression: "",
    eventName: "",
    status: ""
  });

  const dataList = ref<PlanTaskItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  //分页元素
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  //列表元素
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "任务名称",
      prop: "name",
      minWidth: 130
    },
    {
      label: "Cron表达式",
      prop: "cronExpression",
      minWidth: 180
    },
    {
      label: "关联事件",
      prop: "eventName",
      minWidth: 130
    },
    {
      label: "参数",
      prop: "params",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      formatter: (row: any) => (row.status === 1 ? "已启用" : "已禁用")
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 130
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  //按钮类
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  //获取/搜索列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      name: form.name,
      cronExpression: form.cronExpression,
      eventName: form.eventName,
      status: form.status
    };

    http
      .post(changeHttpLink("/api/planTasks"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  //新增、修改操作
  function openDialog(type = "新增", row = {}) {
    const result = addDialog({
      title: `${type}计划任务`,
      props: {
        form: cloneDeep(row),
        type
      },
      width: "500px",
      draggable: true,
      contentRenderer: () => editForm
    });

    if (result && typeof result.then === "function") {
      result.then(() => {
        onSearch();
      });
    } else {
      onSearch();
    }
  }
  //删除
  function handleDelete(row) {
    ElMessageBox.confirm(`是否确认删除ID为${row.id}的计划任务`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/planTasks/delete"), {
            data: { id: row.id }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`删除计划任务成功`, { type: "success" });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }
  //打开修改对话框
  function handleUpdate(row) {
    openDialog("修改", row);
  }
  //页面数据大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }
  //处理当前变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  //处理选择
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
  }
  //表格多选取消
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }
  //批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const ids = curSelected.map(item => item.id);

    ElMessageBox.confirm(`是否确认删除选中的${ids.length}条数据`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/planTasks/batchDelete"), {
            data: { ids }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`批量删除成功`, { type: "success" });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }
  //返回操作函数
  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    onbatchDel
  };
}
